package com.sks.service.privilege.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import com.sks.bean.privilege.SystemPrivilege;
import com.sks.bean.privilege.SystemPrivilegePK;
import com.sks.dao.base.DaoSupport;
import com.sks.service.privilege.SystemPrivilegeService;
import com.sks.utils.StringUtil;

@Service
public class SystemPrivilegeServiceBean extends DaoSupport<SystemPrivilege> implements SystemPrivilegeService {
	
	public void batchSave(List<SystemPrivilege> privileges){
		for(SystemPrivilege p : privileges){
			save(p);
		}
	}
	
	@Override
	public List<SystemPrivilege> getPrivilegeByModule(String... modules) {
		StringBuffer jpql = new StringBuffer("select p from SystemPrivilege p where p.id.module in (");
		for (int i = 0; i < modules.length; i++) {
			if (i == 0) {
				jpql.append("?");
			} else {
				jpql.append(", ?");
			}
		}
		jpql.append(")");
		return this.getListByJpql(jpql.toString(), modules);
	}
	
	@Override
	public boolean hasPrivilege(String username, SystemPrivilegePK pid) {
		List result = getPrivileges(username, pid);
		if (!CollectionUtils.isEmpty(result)) {
			return true;
		}
		return false;
	}
	
	@Override
	public boolean hasPrivilege(String username, String module, String privilege) {
		return hasPrivilege(username, new SystemPrivilegePK(module, privilege));
	}
	
	@Override
	public List<SystemPrivilege> getPrivileges(String username) {
		return getPrivileges(username, null);
	}
	
	@Override
	public List<SystemPrivilege> getPrivileges(String username, SystemPrivilegePK pk) {
		StringBuffer jpql = new StringBuffer("select sp from SystemPrivilege sp join sp.groups gs join gs.employees es where es.username = ?");
		List params = new ArrayList();
		params.add(username);
		if (null != pk && !StringUtil.isEmpty(pk.getModule()) && !StringUtil.isEmpty(pk.getPrivilege())) {
			jpql.append(" and sp.id.module = ? and sp.id.privilege = ?");
			params.add(pk.getModule());
			params.add(pk.getPrivilege());
		}
		return this.getListByJpql(jpql.toString(), params.toArray());
	}
}
